import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:notification_centre/notification_centre.dart';

class JcDiceLoading extends StatefulWidget {
  const JcDiceLoading(
      {super.key, required this.backTap, required this.nextTap});
  final Function backTap;
  final Function nextTap;

  @override
  State<JcDiceLoading> createState() => _JcDiceLoadingState();
}

class _JcDiceLoadingState extends State<JcDiceLoading> {
  List<String> waveNames = [
    'Firework🎆Night',
    'Wave🌊Singer',
    'LostBunny🐰',
    'DreamChaser💫',
    'Gentle🍃Breeze',
    'Rainbow🌈Chimes',
    'Candy🍬Heart',
    'IceCream🍦Knight',
    'Little🍄Maze',
    'FlyingBug🐞',
    'StarGazer🔭',
    'SmileySunflower🌻',
    'SunnySeed🌻',
    'WingsOfColor🦋',
    'GlowWorm🌟',
    'CloudTop⛅️',
    'Bamboo🐼Keeper',
    'CoffeeBuddy🧋',
    'SweetKnight🍰',
    'Ocean🌴Wanderer',
    'Shooting🌠Star',
    'Rose🌹Lover',
    'DeepBlue🐳',
    'WindChaser🌪️',
    'BlackCatMystery🐾',
    'Starry✨Wanderer',
    'SparkleDancer✨',
    'MoonlightFairy🌙',
    'BunnyNebula🐰',
    'Honey🍯Bear',
    'ForestWarrior🌲',
    'SkyKnight🛡️',
    'OceanWhale🐋',
    'NightBreeze🌌',
    'Leaf🍂Poet',
    'CoffeeExplorer☕️',
    'StarGuardian🌟',
    'RainbowDonut🌈',
    'Smiling😄Nomad',
    'Fairy🧚Dream',
    'FireflyGlow🌌',
    'PeachyAlien🍑',
    'Moonlight🌙Guardian',
    'Orange🍊Pie',
    'Thunder⚡Traveler',
    'CatUnderTheStars🐱',
    'Cloud☁️Dreamer',
    'Forest🌲Sprite',
    'Icy❄️Heart',
    'Coffee☕Craze'
  ];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(seconds: 5), () {
        _diceResult();
      });
    });
  }

  _randomIndex(int min, int max) {
    if (max == 0) {
      return 0;
    }
    int num;
    if (max == min) {
      num = min;
    } else {
      num = Random().nextInt(max - min) + min;
    }
    return num;
  }

  _diceResult() {
    String today = _getNowDateTime();

    var wavaNameRecord = JcCache.getInstance().get('wavaNameRecord');
    var wavaUserId = JcCache.getInstance().get('wavaUserId');
    String recordNames = '';
    if (wavaNameRecord == null) {
      wavaNameRecord = [];
    } else {
      wavaNameRecord = jsonDecode(wavaNameRecord);
      for (var element in wavaNameRecord) {
        var userId = element['userId'];
        var wavaName = element['wavaName'];
        if (wavaUserId == userId) {
          recordNames = '$recordNames,$wavaName';
        }
      }
    }

    bool isSueccess = false;
    String name = '';
    while (!isSueccess) {
      int index = _randomIndex(0, waveNames.length);
      String tmpName = waveNames[index];
      if (!recordNames.contains(tmpName)) {
        name = tmpName;
        isSueccess = true;
      }
    }
    wavaNameRecord.add({'userId': wavaUserId, 'wavaName': name, 'time': today});
    JcCache.getInstance().setData('wavaNameRecord', jsonEncode(wavaNameRecord));
    NotificationCenter().postNotification('wavaRecordChange');
    widget.nextTap(name);
  }

  _getNowDateTime() {
    var now = DateTime.now();

    String year = now.year.toString();
    String month = now.month.toString();
    String day = now.day.toString();

    if (now.month < 10) {
      month = '0$month';
    }
    if (now.day < 10) {
      day = '0$day';
    }
    return '$year-$month-$day';
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          // margin: EdgeInsets.only(left: 30.w,right: 30.w),
          width: 336.w,
          height: 241.h,
          padding: EdgeInsets.only(
            left: 15.w,
            right: 15.w,
            top: 24.h,
          ),
          decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(JcImagePath.jcDiceResBg),
                  fit: BoxFit.fill)),
          child: Column(
            children: [_titleWidget(), _loadingWidget(), _btnWidget()],
          ),
        ),
        SizedBox(
          height: 200.h,
        )
      ],
    );
  }

  _titleWidget() {
    return Text(
      'Hey everyone， \nwelcome to NameWave！',
      textAlign: TextAlign.center,
      style: JcTextStyle.poetsenOneRegularTextStyle(24.sp, Colors.white),
    );
  }

  _loadingWidget() {
    return Container(
      margin: EdgeInsets.only(left: 50.w, right: 50.w, top: 15.h, bottom: 15.h),
      height: 50.h,
      width: double.infinity,
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(8.r)),
      child: Image.asset(JcImagePath.jcDiceLoadingGif),
    );
  }

  _btnWidget() {
    return Container(
      margin: EdgeInsets.only(left: 30.w, right: 30.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(
            child: Image.asset(JcImagePath.jcDiceReturn),
            onTap: () {
              widget.backTap();
            },
          ),
          InkWell(
            child: Image.asset(JcImagePath.jcDiceCopy),
          )
        ],
      ),
    );
  }
}
